# 编译器和编译选项
CC       := gcc
CXX      := g++
INCLUDES := -I./include
CFLAGS   := -Wall -Wextra -O2 -g $(INCLUDES)
CXXFLAGS := $(CFLAGS)
LDLIBS   := -lm -lpthread -lcurl -lhcnetsdk -ldhnetsdk
LIB_DIR  := -L./lib
LDFLAGS  := -Wl,-rpath,'$$ORIGIN/lib' -rdynamic $(LIB_DIR)

# 输出目录
BUILD_DIR := build

# 扫描所有 .c/.cpp 源文件
SRC_C   := $(shell find . -name "*.c")
SRC_CPP := $(shell find . -name "*.cpp")

# 目标文件列表
OBJ_C   := $(patsubst %.c,$(BUILD_DIR)/%.o,$(SRC_C))
OBJ_CPP := $(patsubst %.cpp,$(BUILD_DIR)/%.o,$(SRC_CPP))
OBJ     := $(OBJ_C) $(OBJ_CPP)

# 最终可执行文件
TARGET := main.bin

.PHONY: all clean update start stop setup

all: $(TARGET)

# 链接阶段，用 g++
$(TARGET): $(OBJ)
	@echo "链接 $@"
	$(CXX) $^ -o $@ $(LDFLAGS) $(LDLIBS)

# 编译 .c 文件
$(BUILD_DIR)/%.o: %.c
	@echo "编译 C $<"
	@mkdir -p $(dir $@)
	$(CC)   $(CFLAGS)  -c $< -o $@

# 编译 .cpp 文件
$(BUILD_DIR)/%.o: %.cpp
	@echo "编译 C++ $<"
	@mkdir -p $(dir $@)
	$(CXX)  $(CXXFLAGS) -c $< -o $@

# 部署：重启服务
update: $(TARGET)
	@echo "停止服务 leishi.service..."
	sudo systemctl stop leishi.service
	@echo "启动服务 leishi.service..."
	sudo systemctl start leishi.service
	@echo "更新完成！"

stop:
	@echo "停止服务 leishi.service..."
	sudo systemctl stop leishi.service

start:
	@echo "启动服务 leishi.service..."
	sudo systemctl start leishi.service

setup:
	@echo "设置服务..."
	sed -i -e 's/\r//g' ./service.sh
	sudo chmod +x ./service.sh
	sudo ./service.sh
	sudo systemctl daemon-reload
	@echo "设置完成！"

clean:
	@echo "清理构建产物..."
	rm -rf $(BUILD_DIR) $(TARGET)
